<?php
require_once 'db_connection.php';

function get_all_children(){
  $to_return = array();
  $query = 'SELECT * FROM children';
  $result = mysql_query($query);
  $num_rows = mysql_num_rows($result);
  for ($i = 0; $i < $num_rows; ++$i){
    $object = mysql_fetch_assoc($result);
    $to_return[] = $object;
  }
  return $to_return;
}

function get_checkedin(){
  $to_return = array();
  $query = "SELECT * FROM children WHERE checked_in=1";
  $result = mysql_query($query);
  $num_rows = mysql_num_rows($result);
  for ($i = 0; $i < $num_rows; ++$i){
    $object = mysql_fetch_assoc($result);
    $to_return[] = $object;
  }
  return $to_return;
}

function get_checkedout(){
  $to_return = array();
  $query = "SELECT * FROM children WHERE checked_in=0";
  $result = mysql_query($query);
  $num_rows = mysql_num_rows($result);
  for ($i = 0; $i < $num_rows; ++$i){
    $object = mysql_fetch_assoc($result);
    $to_return[] = $object;
  }
  return $to_return;
}

function check_in($name){
  $t = date( 'Y-m-d H:i:s');

  $query = "UPDATE children SET checked_in=1, last_checked_in='$t' WHERE name='$name' ";
  // echo $query;
  $result = mysql_query($query);
  // echo $result;
}

function check_out($name){
  $query = "UPDATE children SET checked_in=0 WHERE name='$name' ";
  $result = mysql_query($query);
}

function format_date_diff($date){
  $now = new DateTime('now');
  $date_diff = date_diff($now, $date);
  $minutes = $date_diff->i;
  $hours = $date_diff->h;
  $days = $date_diff->d;
  if($days>=1){
    return date_format($date, 'm/d/y');
  }
  elseif($hours>=1){
    return "$hours hours ago";
  }
  elseif($minutes > 5){
    return "$minutes minutes ago";
  }
  else{
    return "Just now";
  }
  
  
}

function format_dates($array){
  $children = $array;
  $num_children = count($children);
  for($i = 0; $i < $num_children; $i++){
    $lci = new DateTime($children[$i]['last_checked_in']);
    $d = format_date_diff($lci);
    $children[$i]['last_checked_in'] = $d;       
  }
  return $children;
}

$operation = $_GET['operation'];

//Very basic controller
switch($operation){
  case('get_all_children'):
    $children = get_all_children();
    $to_return = format_dates($children);
    echo json_encode($to_return);
    break;
    
  case('get_checkedin'):
    $children = get_checkedin();
    $result = format_dates($children);
    echo json_encode($result);
    break;
    
  case('get_checkedout'):
    $children = get_checkedout();
    $result = format_dates($children);
    echo json_encode($result);
    break;
    
  case('check_in'):
    $name = $_GET['name'];
    check_in($name);
    break;
    
  case('check_out'):
    $name = $_GET['name'];
    check_out($name);
    break;
    
  default:
    break;
}

// $d = new DateTime("2012-05-14 05:27:41");
// $st = format_date_diff($d);
// print($st);


?>
